import { reactive, onMounted } from 'vue'
import { format } from 'date-fns'
import { parseTime } from '@/common/common'
import { Project } from '@/service/modules/project/types'
import {
  getWorkPublishListReq,
  delTaskReq
} from '@/service/modules/work-publish'

export function useTable() {
  const state = reactive({
    page: 1,
    limit: 10,
    count: 0,
    searchParam: {
      taskType: null,
      name: '',
      departmentId: null
    },
    list: [],
    loading: false,
    currentRecord: {} as Project,
    modAliasModalShow: false,
    modDescModalShow: false,
    modDepartmemtModalShow: false,
    createUserModalShow: false,
    setHiveDbSizeModalShow: false,
    setProjectManagerModalShow: false
  })

  const getList = async () => {
    if (state.loading) return
    state.loading = true

    const { data, count } = await getWorkPublishListReq({
      page: state.page,
      limit: state.limit,
      ...state.searchParam
    })
    state.loading = false
    if (!data) throw Error()
    state.list = data.map((record: Project) => {
      record.createTime = record.createTime
        ? format(parseTime(record.createTime), 'yyyy-MM-dd HH:mm:ss')
        : ''
      record.updateTime = record.updateTime
        ? format(parseTime(record.updateTime), 'yyyy-MM-dd HH:mm:ss')
        : ''
      return record
    })
    state.count = count
  }

  const updateList = () => {
    if (state.list.length === 1 && state.page > 1) {
      --state.page
    }
    getList()
  }
  
  // 下线发布作业
  const delTask = async (id: number, name: string) => {
    window.$dialog.warning({
      title: window.$t('dialog.warningTitle'),
      content: window.$t('project.workpublish.offlinetips') + name,
      positiveText: window.$t('dialog.positiveText'),
      negativeText: window.$t('dialog.negativeText'),
      onPositiveClick: async () => {
        const res = await delTaskReq({ id: id })
        if (res.resp_code === 0) {
          getList()
        }
      }
    })
  }

  const onOperationClick = (
    data: { rowData: Project },
    type:
      | 'offLine'
      | 'gotoDetail'
  ) => {
    state.currentRecord = data.rowData
    switch (type) {
      case 'offLine':
        delTask(data.rowData.id, data.rowData.name)
        break
      case 'gotoDetail':
        console.log('跳转作业详情的代码')
        break
    }
  }

  const changePage = (page: number) => {
    state.page = page
    getList()
  }

  const changePageSize = (limit: number) => {
    state.page = 1
    state.limit = limit
    getList()
  }

  onMounted(() => {
    getList()
  })

  return {
    state,
    changePage,
    changePageSize,
    updateList,
    onOperationClick
  }
}
